import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import fetch from 'API/fetch'
// import { CheckmarkFilled16 as VerifiedIcon } from '@carbon/icons-react';

import Button from '@kuiper-components/button';
import Input from '@kuiper-components/input';

import { name } from '../../../../../../../../package.json';

import s from './VerificationCode.module.css';

function countdown(count, cb) {
	if (count <= 0) return;
	const stid = setTimeout(() => {
		clearTimeout(stid);
		// eslint-disable-next-line standard/no-callback-literal
		cb(count - 1000);
		setTimeout(countdown(count - 1000, cb), 1000);
	}, 1000);
}

export default function VerificationCode({
	className,
	type,
	contact,
	value,
	onChange,
	btnDisabled,
	autoSend,
}) {
	const {
		app: {
			config: {
				[name]: { verificationCodeResendInterval },
			},
		},
	} = window.kuiper;
	const [error, setError] = React.useState('');
	const [count, setCount] = React.useState(0);
	const waitSecond = count >= 0 ? (count / 1000) | 0 : 0;
	const [verificationCodeSended, setSended] = React.useState(false);
	const nodeRef = React.useRef();
	const handleSendCode = e => {
		if (e) {
			e.preventDefault();
			e.stopPropagation();
		}
		const typeMap = {
			phone: 'sms',
			email: 'email'
		}
		return fetch(`/api/v2/alerts/receiver/${typeMap[type]}_verified_code?${type}=${contact}`, { method: 'GET' })
			.then(() => {
				setSended(true);
				setCount(verificationCodeResendInterval);
				countdown(verificationCodeResendInterval, x => setCount(x));
			})
			.catch(error => setError(error.message));
	};

	React.useEffect(() => {
		if (autoSend) {
			handleSendCode();
		}
	}, []);

	return (
		<div className={cn(className, s.verificationCode)}>
			<div className={s.verify}>
				<Input
					className={s.input}
					size="small"
					minLength="6"
					maxLength="6"
					value={value}
					placeholder="验证码"
					onChange={onChange}
				/>
				{verificationCodeSended ? (
					<Button
						className={cn(s.btn, s.resend)}
						size="small"
						disabled={waitSecond > 0}
						onClick={handleSendCode}
					>
						{waitSecond || ''} 再次发送
					</Button>
				) : (
					<Button
						className={cn(s.btn, s.send)}
						size="small"
						onClick={handleSendCode}
						ref={nodeRef}
						disabled={btnDisabled}
						primary
					>
						获取验证码
					</Button>
				)}
			</div>
			{error && <pre className={s.error}>{error.replace(/\[.*?\]/g, '')}</pre>}
		</div>
	);
}

VerificationCode.propTypes = {
	className: PropTypes.string,
	type: PropTypes.string.isRequired,
	verified: PropTypes.bool.isRequired,
	contact: PropTypes.string,
	receiverId: PropTypes.string.isRequired,
	value: PropTypes.string,
	onChange: PropTypes.func.isRequired,
	btnDisabled: PropTypes.bool,
	autoSend: PropTypes.bool,
};

VerificationCode.defaultProps = {
	className: s.VerificationCode,
	value: '',
	verified: false,
	btnDisabled: false,
	autoSend: false,
};
